package homework6.exp5;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author fengq
 */
public class Test5 {
    public static void main(String[] args) throws DocumentException, IOException {

        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/studentsInfo.xml"));
        Element root = document.getRootElement();

        Element element = root.addElement("student");
        Element name1 = element.addElement("name");
        name1.setText("张三");
        Element age1 = element.addElement("age");
        age1.setText("18");
        Element school1 = element.addElement("school");
        school1.setText("人民大学");

        Element element2 = root.addElement("student");
        Element name2 = element2.addElement("name");
        name2.setText("李四");
        Element age2 = element2.addElement("age");
        age2.setText("19");
        Element school2 = element2.addElement("school");
        school2.setText("浙江大学");

        //设置编码格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(new FileWriter("src/studentsInfo.xml"),format);

        writer.write(document);
        writer.close();

    }
}
